package 数组;

/**
 * @Author Weton Li
 * @Date 2021/4/20 12:49
 */
public class 买卖股票最佳时机 {

    public static int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

    public static int errorOrRightmethod(int[] nums){
        int maxP = 0;
        int n = nums.length;
        for (int i = 0; i < n-1; i++) {
            for (int j = i+1; j < n; j++) {
                if (nums[j] - nums[i] > maxP) {
                    maxP = nums[j] - nums[i];
                }
            }
        }
        return maxP;
    }

    public static int method(int[] nums){
        int minP = Integer.MAX_VALUE; // 初始时令其最大，第一个数必默认为最小
        int maxP = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            if (nums[i] < minP) {
                minP = nums[i]; // 首先第一个数为最小
            }else if(nums[i]-minP > maxP){
                maxP = nums[i] -minP; // 第一个数和0做减法，必为当前循环最大利润
            }
        }
        return maxP;
    }

    public static int maxProfit2(int[] prices) {
        if(prices.length == 1 || prices == null){ // 如果只有一个数不存在昨日持股额
            return 0;
        }
        int res = 0;
        for(int i = 1;i<prices.length;i++){
            if(prices[i]>prices[i-1]){
                res += (prices[i]-prices[i-1]); // 如果当前持股比昨日持股多，立即将差值累加。
            }
        }
        return res;
    }
    public static void main(String[] args) {
        int[] input = {7,1,5,3,6,4};
        System.out.println(method(input)); // 5
        System.out.println(maxProfit2(input)); // 7
    }
}
